#include <QtWidgets/QApplication>

#include "utils/VtkUtil.h"

#include "core/AppDirectory.h"
#include "qtmain.h"

// #define QT_MESSAGE_PATTERN = "[%{type}] %{function}:%{line} - %{message}"

void debugMessageOutput(
    QtMsgType type,
    const QMessageLogContext& context,
    const QString& msg
)
{
    Q_UNUSED(context);
    QByteArray txt = QString("").toLocal8Bit();
    QString timestamp =
        QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");

    switch (type) {
    case QtDebugMsg:
        txt += QString("{Debug}\t%1\t%2").arg(timestamp).arg(msg);
        break;
    case QtWarningMsg:
        txt += QString("{Warn }\t%1\t%2").arg(timestamp).arg(msg);
        break;
    case QtCriticalMsg:
        txt += QString("{Criti}\t%1\t%2").arg(timestamp).arg(msg);
        break;
    case QtFatalMsg:
        txt += QString("{Fatal}\t%1\t%2").arg(timestamp).arg(msg);
        // abort(); // deliberately core dump
    }
    cout << QString::fromUtf8(txt).toLocal8Bit().data() << endl;

    try {
        QFile outFile(AppDirectory::get().getAppDocFile("debug.log"));
        outFile.open(QIODevice::WriteOnly | QIODevice::Append);
        QTextStream textStream(&outFile);
        textStream << txt << endl;
    } catch (const std::exception& e) {
        std::cerr << "Exception: " << e.what() << endl;
    } catch (...) {
        std::cerr << "Unknown exception" << endl;
    }
}

int main(int argc, char* argv[])
{
    try {
        VtkUtil::hideOutputWindow();
        QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
        QApplication a(argc, argv);

        qInstallMessageHandler(debugMessageOutput);

        qtMain w;
        w.showMaximized();
        return a.exec();
    } catch (const std::exception& e) {
        std::cerr << "Exception: " << e.what() << endl;
        return 1;
    } catch (...) {
        std::cerr << "Unknown exception" << endl;
        return 1;
    }
}
